package view_api

import (
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
	"gin-vue-admin/model/response"
	"gin-vue-admin/service"
	"gin-vue-admin/service/view_service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func GetUserLists(c *gin.Context){
		var pageInfo request.UsersSearch
		_ = c.ShouldBindQuery(&pageInfo)
		pageInfo.ApplyStatus = 3
		pageInfo.Phone = ``
		if err, list, total := service.GetUsersInfoList(pageInfo); err != nil {
			global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
			response.FailWithMessage("获取失败", c)
		} else {
			allCount ,applyCount ,overCount  := service.GetTotals()
			response.OkWithDetailed(response.PageResult{
				List:     list,
				Total:    total,
				Page:     pageInfo.Page,
				PageSize: pageInfo.PageSize,
				AllCount: allCount,
				ApplyCount: applyCount,
				OverCount: overCount,
			}, "获取成功", c)
		}
}

func UserLogin(c *gin.Context){
	err,res:= view_service.UserLogin(c.Query(`phone`),c.Query(`password`))
	if err != nil{
		response.FailWithMessage(`账号或密码错误`,c)
	}else{
		response.OkWithData(res,c)
	}
}

func GetUserInfoWithPhone(c *gin.Context){
	err,res:= view_service.GetUsers(c.Query(`phone`))
	if err != nil{
		response.FailWithMessage(err.Error(),c)
	}else{
		response.OkWithData(res,c)
	}
}

type UserCreate struct {
	Users model.Users `json:"users"`
	Code int `json:"code"`
}
func CreateUsers(c *gin.Context) {
	var users UserCreate
	_ = c.ShouldBindJSON(&users)
	err,resp := service.GetUserMsgWithPhoneAndCode(users.Users.Phone,users.Code)
	if err != nil{
		fmt.Println(resp)
		response.FailWithMessage("验证码错误", c)
		return
	}
	users.Users.CName = users.Users.Name
	users.Users.ApplyStatus = 1
	if users.Users.Name == `` || users.Users.Phone == `` || users.Users.Password == ``{
		response.FailWithMessage("请输入完整的注册信息", c)
		return
	}
	if err := service.CreateUsers(users.Users); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
		response.FailWithMessage("账号信息已存在", c)
	} else {
		response.OkWithData(users.Users.Phone, c)
	}
}

func UpdateUsers(c *gin.Context){
	var users model.Users
	_ = c.ShouldBindJSON(&users)
	users.ApplyStatus = 2
	if err := service.UpdateUsers(users); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Any("err", err))
		response.FailWithMessage("提交信息失败", c)
	} else {
		response.OkWithMessage("提交信息成功，等待审核", c)
	}
}
